package com.ming.user.config;

import com.ming.user.constant.BasicAuthConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description Feign客户端调用传递授权token
 * @return
 * @date 2021/2/4 17:15
 * @auther yanming.fu
 */
@Slf4j
@Component
public class OAuth2FeignConfig implements RequestInterceptor {


    /**
     * @param template
     * @return void
     * @date 2021/2/4 17:15
     * @auther yanming.fu
     */
    @Override
    public void apply(RequestTemplate template) {
        log.error("feign 调用拦截 传递资源服务器token Start>>>>>>>>>>>>>>>>>>>>>");
        // 1 我们可以从request的上下文环境里面获取token
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        String header = null ;
        if (requestAttributes == null) {
           log.info("没有请求的上下文,故无法进行token的传递");
            header = "bearer "+ BasicAuthConstant.INSIDE_TOKEN ;
        }else{
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            header = request.getHeader(HttpHeaders.AUTHORIZATION); // 获取我们请求上下文的头里面的AUTHORIZATION
        }

        if (!StringUtils.isEmpty(header)) {
            template.header(HttpHeaders.AUTHORIZATION, header);
          log.info("本次token传递成功,token的值为:{}", header);
        }

        log.error("feign 调用拦截 传递资源服务器token END>>>>>>>>>>>>>>>>>>>>>");
    }
}
